//
//  Ch2Controller.swift
//  learn-gl-es-swift
//
//  Created by LimitLiu on 2019/6/30.
//  Copyright © 2019 LimitLiu. All rights reserved.
//

import UIKit
import GLKit

struct SceneVertex2_1 {
    let positionCoords: GLKVector3
}

class Ch2_1Controller: GLKViewController {
    var vertexBufferID: GLuint = GLuint()
    var baseEffect = GLKBaseEffect()
    var vertices: [SceneVertex2_1] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        glConfig()
    }
    deinit {
        let view = self.view as! GLKView
        EAGLContext.setCurrent(view.context)
        if vertexBufferID != 0 {
            glDeleteBuffers(1, &vertexBufferID)
            vertexBufferID = 0
        }
        EAGLContext.setCurrent(nil)
    }
}

extension Ch2_1Controller {
    private func glConfig () {
        vertices = [
            SceneVertex2_1(positionCoords: vec(-0.5, -0.5, 0.0)),
            SceneVertex2_1(positionCoords: vec(0.5, -0.5, 0.0)),
            SceneVertex2_1(positionCoords: vec(-0.5, 0.5, 0.0)),
        ]
        let view = self.view as! GLKView
        view.context = EAGLContext(api: .openGLES2)!
        EAGLContext.setCurrent(view.context)
        baseEffect.useConstantColor = GLboolean(GL_TRUE)
        baseEffect.constantColor = vec(0.3, 0.6, 0.3, 1.0)
        glClearColor(0.5, 0.7, 0.5, 1.0)
        glGenBuffers(1, &vertexBufferID)
        glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexBufferID)
        glBufferData(GLenum(GL_ARRAY_BUFFER), vertices.sizeof(),
                     vertices, GLenum(GL_STATIC_DRAW))
    }
}

extension Ch2_1Controller {
    override func glkView(_ view: GLKView, drawIn rect: CGRect) {
        baseEffect.prepareToDraw()
        glClear(GLbitfield(GL_COLOR_BUFFER_BIT))
        glEnableVertexAttribArray(0)
        glVertexAttribPointer(0, 3, GLenum(GL_FLOAT),
                              GLboolean(GL_FALSE),
                              GLsizei(MemoryLayout<SceneVertex2_1>.size), nil)
        glDrawArrays(GLenum(GL_TRIANGLES), 0, GLsizei(vertices.count))
    }
}
